import 'package:dk_flutter_base/dk_core.dart';
import 'package:dk_flutter_base/dk_ui.dart';
import 'package:dk_flutter_module_sale/common/config/page_base_common.dart';
import 'package:dk_flutter_module_sale/common/user_track/user_track.dart';
import 'package:dk_flutter_module_sale/config/cache_info_key.dart';
import 'package:dk_flutter_module_sale/config/route/common_widget_route.dart';
import 'package:dk_flutter_module_sale/config/route/sale_in_widget_route.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/supervisor_visit/bean/bean_supervisor_visit.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/supervisor_visit/widget/supervisor_visit_header.dart';
import 'package:dk_flutter_module_sale/sale/sale_in/supervisor_visit/widget/supervisor_visit_listitem_content.dart';
import 'package:dk_flutter_module_sale/config/native_config.dart';
import 'package:dk_flutter_module_sale/sale/api/sale_in_api.dart';

class VisitBottomModel with SelectModel {
  String title;
  String content;

  VisitBottomModel.option(this.title, this.content) {
    initSelectModel(title, content);
  }
}

/*主管陪访列表*/
@ARoute(url: SaleInWidgetRoute.SALE_IN_SUPERVISOR_VISIT)
class SupervisorVisit extends CommonPageWithTrack {
  SupervisorVisit(BoostRouteOption option) : super();

  List<SelectModel> getListBottom() {
    List<VisitBottomModel> listBottom = List();
    String baseUrl;
    if (Env?.value?.type == EnvType.RELEASE) {
      baseUrl = "https://salerapi.danke.com";
    } else {
      var extent = Env?.value?.getExtent(CacheInfoKey.KEY_CONFIG);
      if (extent is NativeConfig) {
        baseUrl = extent.saleInBaseUrl;
      }
    }
    listBottom.add(VisitBottomModel.option(
        baseUrl +
            "/saler-app/web-view/api-page/landlord/#/manage/accompany-visit/survey",
        "上门实勘"));
    listBottom.add(VisitBottomModel.option(
        baseUrl +
            "/saler-app/web-view/api-page/landlord/#/manage/accompany-visit/risk-control",
        "风控量房"));
    listBottom.add(VisitBottomModel.option(
        baseUrl +
            "/saler-app/web-view/api-page/landlord/#/manage/accompany-visit/contract-sign",
        "合同签约"));
    listBottom.add(VisitBottomModel.option(
        baseUrl +
            "/saler-app/web-view/api-page/landlord/#/manage/accompany-visit/channel-dev",
        "渠道开发"));
    return listBottom;
  }

  @override
  void trackStatistics() {
    UserTrack.trackViewScreen("收房主管陪访-新建陪访", null);
  }

  @override
  DkAppBar getAppBar(CommonPageBloc pageBloc) {
    return DkAppBar(DKAppBarParams.withBackMenu(
      pageBloc.context,
      [
        InkWell(
          child: Container(
            padding: EdgeInsets.only(right: 15),
            alignment: AlignmentDirectional.center,
            child: Text(
              "新建陪访",
              textAlign: TextAlign.justify,
            ),
          ),
          onTap: () {
            DkBottomDialog.create(BottomDialogOption((BuildContext context) {
              return TransSelectBottom(
                getListBottom(),
                TransSelectBottomOption(),
              );
            }, handleResult: (SelectModel value) {
              if (null != value) {
                Future.delayed(Duration(milliseconds: 200)).then((time) {
                  RouteUtil.goPage(value.key);
                });
              }
            })).show(pageBloc.context);
          },
        ),
      ],
      titleContent: "主管陪访",
    ));
  }

  void onInitState(CommonPageBloc pageBloc) {
    Map<String, dynamic> paramsMap = Map();
    paramsMap["page"] = 1;
    paramsMap["page_num"] = 10;
    pageBloc.pageHttpGet(
        path: SaleInApi.supervisorVisitList,
        queryMap: paramsMap,
        widgetBuilderByData: (dynamic data) {
          BeanSupervisorVisit visitBean =
              BeanSupervisorVisit.fromJson(data) ?? BeanSupervisorVisit();
          return SupervisorWidget(visitBean, paramsMap, pageBloc);
        });
  }
}

class SupervisorWidget extends StatefulWidget {
  final BeanSupervisorVisit visitBean;
  final Map<String, dynamic> paramsMap;
  final CommonPageBloc pageBloc;

  SupervisorWidget(this.visitBean, this.paramsMap, this.pageBloc);

  @override
  State<StatefulWidget> createState() {
    return SupervisorState(this.visitBean, this.paramsMap, this.pageBloc);
  }
}

class SupervisorState extends State<SupervisorWidget> {
  CommonPageBloc pageBloc;
  List<DataListBean> dataList = List();
  Map<String, dynamic> paramsMap;
  BeanSupervisorVisit visitBean;
  DkEasyRefreshController easyRefreshController;
  SupervisorState(this.visitBean, this.paramsMap, this.pageBloc);
  int pageIndex = 1;

  @override
  void initState() {
    super.initState();
    dataList = visitBean.data ?? List<DataListBean>();
    easyRefreshController = DkEasyRefreshController();
    FlutterBoost.singleton.addBoostContainerLifeCycleObserver((
        ContainerLifeCycle state, BoostContainerSettings settings) {
      if(settings.name != SaleInWidgetRoute.SALE_IN_SUPERVISOR_VISIT) {
        return;
      }
      if(state == ContainerLifeCycle.Appear) {
        refreshPage();
      } else if(state == ContainerLifeCycle.Destroy) {
        FlutterBoost.singleton.observersHolder.removeObserver(this);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        mainAxisSize: MainAxisSize.max,
        children: getAllItems(visitBean),
      ),
    );
  }

  Future<void> refreshPage() async {
    this.pageIndex = 1;
    paramsMap['page'] = this.pageIndex;
    pageBloc.dataHttpGet(
        path: SaleInApi.supervisorVisitList,
        queryMap: paramsMap,
        handleResult: (dynamic data) {
          BeanSupervisorVisit visitResult = BeanSupervisorVisit.fromJson(data);
          visitBean = visitResult;
          setState(() {
            easyRefreshController.finishRefresh(success: true);
          });
        },
        showLoading: false,
        handleFailResult: (dynamic data1, dynamic data2) {
          easyRefreshController.finishRefresh(success: false);
        },
        handleErrorCode: (dynamic data1) {
          easyRefreshController.finishRefresh(success: false);
        });
  }

  Future<void> loadMore() async {
    paramsMap['page'] = (++this.pageIndex);
    pageBloc.dataHttpGet(
        path: SaleInApi.supervisorVisitList,
        queryMap: paramsMap,
        handleResult: (dynamic data) {
          BeanSupervisorVisit visitResult = BeanSupervisorVisit.fromJson(data);
          visitBean.data.addAll(visitResult.data);
          setState(() {
            easyRefreshController.finishLoad(
                success: true,
                noMore: this.pageIndex >= this.visitBean.lastPage);
          });
        },
        showLoading: false,
        handleFailResult: (dynamic data1, dynamic data2) {
          easyRefreshController.finishLoad(success: false);
        },
        handleErrorCode: (dynamic data1) {
          easyRefreshController.finishLoad(success: false);
        });
  }

  List<Widget> getAllItems(BeanSupervisorVisit visitBean) {
    bool noMore = this.pageIndex >= this.visitBean.lastPage;
    List<Widget> datas = List<Widget>();
    datas.add(VisitHeaderWidget(HeaderOption.hasButton(visitBean, () {
      RouteUtil.goPage(SaleInWidgetRoute.SALE_IN_SUPERVISOR_LASTWEEK_VISIT,
          animated: true);
    })));

    datas.add(
      Expanded(
        flex: 1,
        child: Container(
          color: Colors.white,
          child: DkRefreshListWidget.custom(
              controller: easyRefreshController,
              onLoad: noMore ? null : this.loadMore,
              onRefresh: this.refreshPage,
              emptyWidget: this.visitBean.data.length == 0
                  ? LogicPage(PortalConfig.smallEmptyPageParam)
                  : null,
              slivers: <Widget>[
                SliverList(
                  delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
                      DataListBean dataListBean = visitBean.data[index];
                      return getListItemCell(dataListBean);
                    },
                    childCount: this.visitBean.data.length,
                  ),
                ),
              ]),
        ),
      ),
    );

    return datas;
  }

  Widget getListItemCell(DataListBean dataListBean) {
    dataListBean.status ??= "";
    dataListBean.executeType ??= " ";
    String listId = "任务号: " + dataListBean.id.toString();
    String name = "销售: " + (dataListBean?.dealerName ?? "");
    String date = "陪访时间: " + (dataListBean.visitAt ?? "");
    double topPadding = stringBlank(dataListBean.status) ? 0 : 4;
    double leftPadding = stringBlank(dataListBean.status) ? 0 : 8;
    return Container(
      margin: EdgeInsets.only(bottom: 10),
      color: Colors.white,
      child: InkWell(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            SupervisorListItemContent(
                SupervisorListItemParams(listId, name, date)),
            Column(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(right: 15),
                  padding: EdgeInsets.only(top: 13),
                  child: Align(
                    alignment: Alignment.centerRight,
                    child: Container(
                      padding: EdgeInsets.fromLTRB(
                          leftPadding, topPadding, leftPadding, topPadding),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(14),
                          topRight: Radius.circular(14),
                          bottomRight: Radius.circular(14),
                        ),
                        //color: Color(int.parse("0xff" + (dataListBean.statusColor))),
                        color: Colors.blue,
                      ),
                      child: Text(
                        dataListBean.status,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 12,
                        ),
                      ),
                    ),
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(right: 15, top: 6, bottom: 20),
                  child: Align(
                    alignment: Alignment.centerRight,
                    child: Container(
                      child: Text(
                        dataListBean.executeType,
                        style: TextStyle(
                          color: Color(0xff666666),
                          fontSize: 12,
                        ),
                      ),
                    ),
                  ),
                )
              ],
            ),
          ],
        ),
        onTap: () {
          RouteUtil.goPage(dataListBean.url);
        },
      ),
    );
  }
}
